/**
  * 用户基本信息的store
  * @author: Ruan Jiazhen
  * @date: 2024-04-29 10:36:17
* */
import { reqUploadImage } from '@/api/api-others';
import {
    requestBindOpenId,
    requestInfo,
    requestToken,
    reqUpdateAvatarAndName
} from '@/api/api-user';
import { defaultUserInfo } from '@/static/constant/user-constant';
import { setToken } from '@/utils/local-data';

export const useUser = defineStore('user', () => {
  // #region 是否登录相关
  const isLogin = ref(false);

  /** 检查本地token状态，并根据该状态设置当前是否登录 */
  const checkToken = () => {
    const token = uni.getStorageSync('token');
    console.log("check",token)
    if (token) {
      isLogin.value = true;
    } else {
      isLogin.value = false;
    }
  };

  /** 设置登录状态 */
  const setLoginStatus = (status: boolean) => {
    isLogin.value = status;
  };

  // #endregion


  // #region 用户信息相关

  /** 用户信息 */
  const userInfo = ref<UserInfo>(defaultUserInfo);

  /**
   * 上传并修改用户头像和昵称
   * @param temAvatarPath 临时头像路径
   */
  const uploadAvatarAndName = async (temAvatarPath: string) => {
    let avatarPath = userInfo.value.avatar;

    if (temAvatarPath) {
      let uploadRes: any = null;
      // 上传头像
      uploadRes = (await reqUploadImage(temAvatarPath)).res;
      avatarPath = JSON.parse(uploadRes.data).data.filePath;
    }

    // 修改用户信息
    const updateRes: any = await reqUpdateAvatarAndName(
      avatarPath,
      userInfo.value.nickname,
    );
    console.log('updateRes', updateRes);

    userInfo.value.avatar = avatarPath;
  };

  // #endregion

  /** 获取并设置token */
  const getToken = (code: string) => new Promise((resolve, reject) => {
    console.log('getToken', code);
    requestToken(code, '')
      .then((res: any) => {
        const resData: GetTokenResData = res.data;
        const { token } = resData.data;
        setToken(token ?? '');

        // 设置userInfo中的手机号
        userInfo.value.phone = resData.data.phone;
        console.log('userInfo', userInfo.value);
        // 判断token是否为'0'，为'0'则返回错误
        if (token != '0') {
          resolve(token);
        } else {
          reject('token为0');
        }
      })
      .catch((err: any) => {
        reject(err);
      });
  });

  /** 获取并设置用户信息、喵豆情况、任务情况
   * @returns void
   * @description 通过接口获取用户信息、喵豆情况、任务情况，并设置到对应的ref变量中
   */
  const getInfo = async () => {
    const res: any = await requestInfo();
    const resData: UserInfoResData = res.data;
    console.log('resData', resData);
    // 设置用户信息
    userInfo.value = {
      ...userInfo.value,
      nickname: resData.data.emcee_name,
      avatar: resData.data.avator,
      phone: resData.data.phonenumber,
      userId: resData.data.id,
      mediaNum: resData.data.mediaNum,
      my_gain: resData.data.sjsp_account,
      daiLing: resData.data.sjsp_account_re,
      totalIncome: resData.data.sjsp_accountAdd,
      zfb_name: resData.data.zfb_name || '',
      zfb_account: resData.data.zfb_account || '',
      is_bind_openid: resData.data.wx_openid_activity ? 'true' : '',
    };
    // 绑定openid
    if (userInfo.value.is_bind_openid) return;
    uni.login({
      success: async (res) => {
        const bindRes = await requestBindOpenId(res.code);
        console.log('1111', bindRes);
      },
    });
  };

  /** 领取奖励后更新用户的待领金额，以及用户的奖励余额 */
  const updateAccountRemain = () => {
    userInfo.value.my_gain = String(
      Number(userInfo.value.my_gain) + Number(userInfo.value.daiLing),
    );
    userInfo.value.daiLing = '0';
  };

  const resetLoginStatus = () => {
    uni.removeStorageSync('token');
    userInfo.value.nickname = '';
    userInfo.value.avatar = '';
    userInfo.value.phone = '';
    userInfo.value.userId = '';
    userInfo.value.my_gain = '0';
    userInfo.value.video_account = '0';
    userInfo.value.daiLing = '0';
    userInfo.value.mediaNum = '0';
    userInfo.value.totalIncome = '0';
    userInfo.value.zfb_name = '';
    userInfo.value.zfb_account = '';
    userInfo.value.is_bind_openid = '';
    userInfo.value.video_account = '0';
  };

  /** 绑定支付宝后更新状态 */
  const updateZfbInfo = (info: { zfb_name: string; zfb_account: string }) => {
    userInfo.value.zfb_name = info.zfb_name || '';
    userInfo.value.zfb_account = info.zfb_account || '';
  };

  /** 提现成功后更新余额 */
  const updateMyGain = (money: string) => {
    userInfo.value.my_gain = String(
      Number(userInfo.value.my_gain) - Number(money),
    );
  };

  return {
    isLogin,
    checkToken,
    setLoginStatus,

    userInfo,
    uploadAvatarAndName,
    getToken,
    getInfo,
    resetLoginStatus,
    updateAccountRemain,
    updateZfbInfo,
    updateMyGain,
  };
});
